import json

from django.shortcuts import render, redirect, reverse

# Create your views here.
from django.http import HttpResponse, JsonResponse


# /weather1/beijing/2018
def weather1(request, city, year):
    """提取url参数数据，位置参数"""
    print('city=%s' % city)
    print('year=%s' % year)
    return HttpResponse("weather1")


# /weather2/beijing/2018,取得的值不对
def weather2(request, year, city):
    """提取url参数数据，位置参数"""
    print('city=%s' % city)
    print('year=%s' % year)
    return HttpResponse("weather2")


# /weather3/beijing/2018/   weather4/(?P<city>[a-z]+)/(?P<year>\d{4})/
def weather3(request, year, city):
    """提取url参数数据，位置参数"""
    print('city=%s' % city)
    print('year=%s' % year)
    return HttpResponse("weather3")


# weather3/beijing/2018/?a=10&b=20&a=30,路由只匹配斜杠后面和问号前面的内容
def weather4(request, year, city):
    """提取问号后⾯面的查询字符串"""
    print('city=%s' % city)
    print('year=%s' % year)

    a = request.GET.get('a')
    b = request.GET.get('b')
    a_list = request.GET.getlist('a')
    print(a, b, a_list)
    return HttpResponse("weather4")


# url(r'^get_body/$', views.get_body),
def get_body(request):
    """获取请求体中表单数据"""
    a = request.POST.get('name')
    b = request.POST.get('age')
    alist = request.POST.getlist('num')
    print(a)
    print(b)
    print(alist)
    return HttpResponse('OK')


def get_body_json(request):
    """获取请求体中非表单类型json数据"""
    json_str = request.body
    json_str = json_str.decode()
    req_data = json.loads(json_str)
    print(req_data['name'])
    print(req_data['num'])

    # AnonymousUser 匿名用户 None
    # request.user 可以获取到当前登录的用户
    print(request.user)

    return HttpResponse('OK')


def response_demo(request):
    """响应对象"""
    # HttpResponse(content=响应体, content_type=响应体数据类型, status=状态码)
    # return HttpResponse(content="Hello", content_type='text/html', status=200)
    # return HttpResponse(content="Hello", content_type='text/html', status=301)
    # 或者
    response = HttpResponse('python')
    response['NB'] = 'True'  # 自定义响应头
    return response


def json_response_demo(request):
    """响应json数据"""
    # JSON字典中的引号必须是双引号
    # return JsonResponse({"hobby": "reading", "subject": "math"})
    # 如果JsonResponse响应的不是字典数据时，需要设置safe=False
    return JsonResponse([{"name": "james", "age": 34}, {"name": "harden", "age": 29}], safe=False)


def redirect_demo(request):
    # 反向解析：通过视图找路由
    # 正向解析：通过路由找视图

    # 如果通过路由别名去进行反向解析时,它会在工程中进行全局搜索,不是找当前子应用中的
    # 如果想要进行指定反向解析查询的范围,可以给子应用设置路由的命名空间
    # print(reverse("index"))

    # 如果给子应用加了命名空间后,反向解析的格式只能是 ('命名空间:路由别名')  如果没有设置命名空间时,reverse中可以用函数名不加引号/直接用路由别名
    print(reverse('request_response:index'))
    # return HttpResponse('OK')

    # 路由最前面加 / 表示从根路由进行重定义,如果没有加 / 表示从当前路径进行重定向
    # return redirect('/users/index/')
    return redirect(reverse('users:index'))


def cookie_demo(request):
    """cookie的读写"""
    response = HttpResponse('ok')
    response.set_cookie("name", "curry", max_age=3600)
    # request.COOKIES为字典类型
    print(request.COOKIES.get('name'))

    return response


def session_demo(request):
    """session读写"""
    # 设置session
    # 为什么session需要通过请求对象去设置或读取: 因为session依赖cookie
    request.session['name'] = 'Durant'
    # 读取
    # 当我们进行设置session时会生成一个sessionid 然后通过response对象设置到cookie并保存到浏览器上
    # 当我们要读取session需要通过请求对象带过来的cookie中的sessionid才能取到这条session记录,再通过name键取到对应的value
    print(request.session['name'])

    return HttpResponse('OK')
